<?php
// This controller handles the logic for the registration pages

class RegistrationController extends Controller
{
		/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}
	
	public function actionSupplier()
	{
		$this->register(2);
	}
	
	public function actionBuyer()
	{
		$this->register(1);
	}
			
	public function actionCheckValid()
	{	
		if(Yii::app()->request->isAjaxRequest)
		{
			$model=new Users;
			$model->scenario='checkvalid';
			$model->user_name=$_POST['Users']['user_name'];
			if(!$model->validate())
				echo "User Name \"".$_POST['Users']['user_name']."\" has already been taken";
		}
	}
	
	public function actionOrgInfo()
	{
		if(Yii::app()->request->isAjaxRequest)
		{
			$data=Organizations::model()->getOrgInfo($_POST['Organizations']['organization_name']);
			echo CJSON::encode($data);
		}
	}
	
	public function actionAutocompleteOrg()
	{
		$arr = Organizations::model()->searchOrgName($_GET['term']);
		$res = array();
		foreach($arr as $org)
		{
			$res[] = array(
				'label' => $org['organization_name'],
				'value' => $org['organization_name'],
				'id' => $org['organization_ID'],
			);
		}
		echo CJSON::encode($res);
	}
	public function processData($type)
	{
			if(isset($_POST['Users']))
			{
				//set users' attributes
				$model->user_name=$_POST['Users']['user_name'];
				if($_POST['Users']['password']!=null)
					$model->password=$_POST['Users']['password'];
				if($_POST['Users']['password2']!=null)
					$model->password2=$_POST['Users']['password2'];
				$model->contact_first_name=$_POST['Users']['contact_first_name'];
				$model->contact_last_name=$_POST['Users']['contact_last_name'];
				$model->address1=$_POST['Organizations']['address1'];
				$model->address2=null;
				$model->state=$_POST['Organizations']['state'];
				$model->city=$_POST['Organizations']['city'];
				$model->zip=$_POST['Organizations']['zip'];
				$model->phoneNumber=$_POST['Users']['phoneNumber'];
				$model->faxNumber=null;
				$model->emailAddress=$_POST['Users']['emailAddress'];
				$model->user_type_ID=$type;
				$model->user_role_type_ID=2;
				$model->organization_ID=Organizations::model()->searchOrgID($_POST['Organizations']['organization_name']);
				//start transaction now
				$transaction=Yii::app()->db->beginTransaction();
				//if user create a new organization
				if($model->organization_ID==null)
				{
					$model->user_role_type_ID=1;
					$org_model->organization_name=$_POST['Organizations']['organization_name'];
					$org_model->address1=$_POST['Organizations']['address1'];
					$org_model->address2=null;
					$org_model->city=$_POST['Organizations']['city'];
					$org_model->state=$_POST['Organizations']['state'];
					$org_model->zip=$_POST['Organizations']['zip'];
					$org_model->fed_ID=$_POST['Organizations']['fed_ID'];
					$org_model->contact_first_name=$_POST['Users']['contact_first_name'];
					$org_model->contact_last_name=$_POST['Users']['contact_last_name'];
					$org_model->DBA=$_POST['Organizations']['DBA'];
					$org_model->phone_number=$_POST['Users']['phoneNumber'];
					$org_model->email_address=$_POST['Users']['emailAddress'];
					$org_model->organization_type_ID=$_POST['Organizations']['organization_type_ID'];
					if($org_model->save())
					{
						//assign the new organization ID to the user's attribute
						$model->organization_ID=$org_model->organization_ID;
						if(isset($_POST["organization_products"]))
						{
							//save entry to the organization_products table from the combo box
							for($i=0;$i<count($_POST["organization_products"]);$i++)
							{
								$up_model=new OrgProductRelation;
								$up_model->product_ID=$_POST["organization_products"][$i];
								$up_model->organization_ID=$model->organization_ID;
								if(!$up_model->save())
								{
									echo "<label style='color:#FF0000'>".$up_model->getErrors()."</label>";
									$transaction->rollback();
									return;
								}
							}
						}
						else
						{
							echo "<label style='color:#FF0000'>you must select at least one product</label>";
							$transaction->rollback();
							return;
						}
					}
					else
					{
						$transaction->rollback();
						return;
					}
				}
				if($model->validate())
				{
					$model->password=md5($_POST['Users']['password'], true);
					$model->password2=md5($_POST['Users']['password2'], true);
					$model->save(false);//don't run validation
					//commit the creations
					$transaction->commit();
					//login and forward to the thank you page
					$identity = new Useridentity($model->user_name, $model->password);
					$identity->setState('userID', $model->user_ID);
					$identity->setState('userType', substr(Yii::app()->params['userTypes'][$model->user_type_ID],0,1));
					$identity->setState('roleType', Yii::app()->params['userRoles'][$model->user_role_type_ID]);
					Yii::app()->user->login($identity);
					$this->redirect(Yii::app()->request->baseUrl."/thank");
					return;
				}
				else
				{
					$transaction->rollback();
				}
			}
	}
	public function register($type)
	{
		if(Yii::app()->user->isGuest)
		{
			$model=new Users;
			$org_model=new Organizations;
			$model->scenario='register';
			$org_model->scenario='register';
			$this->processData($type);
			$this->render(Yii::app()->params['userTypes'][$type],
									 	array('model'=>$model, 'org_model'=>$org_model));
		}
		else
		{
			echo 'please register after you logout. redirect you to the last URL you visited.';
			header("refresh:3;url=".Yii::app()->request->baseUrl);
		}
	}
}
?>
